import Taro from "@tarojs/taro";
import axios, {  AxiosPromise, AxiosRequestConfig } from "axios";
import { getGlobalData } from "..";

const uploadInstance = axios.create({ timeout: 600000, baseURL: BASE_URL });

/**
   * 使用 form 表单上传文件
   * @param url 请求接口 url
   * @param params 请求参数
   * @param files 文件列表
   */
export const uploadFiles = async (url: string,
    files: AnyObjType[] = [],
    params?: AnyObjType,
    config?: AxiosRequestConfig):Promise<AxiosPromise<CustomResponse>> => {
    config = {
        headers: { "Content-Type": "multipart/form-data","Authorization":`Bearer ${getGlobalData("accessToken")}` },
        method: "post",
        params: {},
        url: url,
        ...config,
    };

    const formData = new FormData();
    if ("object" === typeof params) {
        for (const key in params) {
            if (Object.prototype.hasOwnProperty.call(params, key)) {
                const value = params[key];
                config.params[key] = value;
                formData.append(key, value);
            }
        }
    }
    if (files && files.length > 0) {
        files.forEach(file => {
            // @ts-ignore
            formData.append("files", file);
        });
    }
    config.data = formData;
    Taro.showLoading({ title:"文件上传中...",mask:true });
    const res = await uploadInstance(config);
    Taro.hideLoading();
    return res;
};
